<template>
    <view class="container">
        <!-- 顶部品牌区 -->
        <view class="brand-section">
            <!-- 顶部品牌区改为轮播图 -->
            <swiper class="brand-swiper" indicator-dots autoplay interval="5000">
                <swiper-item>
                    <image class="brand-banner" src="/static/icon/轮播图1.jpg" mode="widthFix" />
                </swiper-item>
                <swiper-item>
                    <image class="brand-banner" src="/static/icon/轮播图2.jpg" mode="widthFix" />
                </swiper-item>
                <swiper-item>
                    <image class="brand-banner" src="/static/icon/轮播图3.jpg" mode="widthFix" />
                </swiper-item>
            </swiper>
            <view class="shop-info">
                <view class="business-info">
                    <text class="shop-name">小A的棋牌店</text>
                    <text class="business-time">营业时间：24小时营业</text>
                    <text class="business-address">福建理工大学</text>
                </view>
                <view class="quick-actions">
                    <view class="action-btn">
                        <image src="/static/icon/导航.png" class="action-icon" />
                        <text>导航</text>
                    </view>
                    <view class="action-btn">
                        <image src="/static/icon/电话.png" class="action-icon" />
                        <text>电话</text>
                    </view>
                </view>
            </view>
        </view>
        <!-- 功能模块区 -->
        <view class="feature-section">
            <view class="feature-item" @click="showWifiPopup">
                <view class="feature-img">
                    <image src="/static/icon/wifi.png" class="feature-icon" />
                </view>
                <text class="feature-text">WiFi连接</text>
            </view>
            <view class="feature-item" @click="goToVoucher">
                <view class="feature-img">
                    <image src="/static/icon/团购.png" class="feature-icon" />
                </view>
                <text class="feature-text">团购验券</text>
            </view>
            <view class="feature-item" @click="goToRecharge">
                <view class="feature-img">
                    <image src="/static/icon/会员充值.png" class="feature-icon" />
                </view>
                <text class="feature-text">会员充值</text>
            </view>
            <view class="feature-item">
                <view class="feature-img">
                    <image src="/static/icon/订单续费.png" class="feature-icon" />
                </view>
                <text class="feature-text">订单续费</text>
            </view>
            <view class="feature-item">
                <view class="feature-img">
                    <image src="/static/icon/开门.png" class="feature-icon" />
                </view>
                <text class="feature-text">开门</text>
            </view>
        </view>
        <!-- 房间预订区 -->
        <view class="room-section">
            <view class="section-title">房间列表</view>
            <view v-if="roomList.length === 0" class="empty-room">
                <text>暂无可预订房间</text>
            </view>
            <view v-else>
                <view class="room-card" v-for="(room, index) in roomList" :key="room.id">
                    <image class="room-image" :src="room.image_url" />
                    <view class="room-info">
                        <text class="room-title">{{room.name}}</text>
                        <view class="room-tags">
                            <text class="tag" v-for="(tag, tagIndex) in room.tags" :key="tagIndex">{{tag}}</text>
                        </view>
                        <view class="price-info">
                            <view class="price-wrapper">
                                <view class="price">
                                    <text class="unit">¥</text>
                                    <text class="amount">{{room.hourly_price}}</text>
                                    <text class="unit">/小时</text>
                                </view>
                                <view class="package" v-if="room.package_hours && room.package_price">
                                    <text>{{room.package_hours}}小时套餐：</text>
                                    <text class="package-price">¥{{room.package_price}}</text>
                                </view>
                            </view>
                            <button class="book-btn" @click="goToReserve(room.id)">预订</button>
                        </view>
                    </view>
                </view>
                <view v-if="hasMoreRooms" class="load-more" @click="loadMoreRooms">
                    <text>加载更多</text>
                </view>
            </view>
        </view>
        <!-- 底部导航栏 -->
        <tab-bar active="home"></tab-bar>
        <!-- WiFi连接弹窗 -->
        <wifi-popup :visible="wifiPopupVisible" @update="handleWifiPopupUpdate"></wifi-popup>
    </view>
</template>
<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import TabBar from '@/components/tabBar/TabBar.vue';
import WifiPopup from '@/components/WifiPopup.vue';
import request from '@/utils/request';

// 类型声明
declare const uni: any;

// 房间数据接口定义
interface IRoom {
    id: string | number;
    name: string;
    image_url: string;
    tags: string[];
    hourly_price: number;
    package_hours?: number;
    package_price?: number;
    status?: string;
    description?: string;
}

// WiFi弹窗状态
const wifiPopupVisible = ref(false);

// 房间数据
const roomList = ref<IRoom[]>([]);
const currentPage = ref(1);
const hasMoreRooms = ref(false);
const isLoading = ref(false);

// 加载房间列表
const loadRooms = async (page = 1, reset = false) => {
    if (isLoading.value) return;
    
    try {
        isLoading.value = true;
        const res = await request.get('/api/mobile/room/list', {
            page,
            limit: 5 // 每页5条数据
        });
        
        if (res.code === 200) {
            if (reset) {
                roomList.value = res.data.rooms;
            } else {
                roomList.value = [...roomList.value, ...res.data.rooms];
            }
            
            // 判断是否有更多数据
            hasMoreRooms.value = roomList.value.length < res.data.pagination.total;
            currentPage.value = page;
        } else {
            uni.showToast({
                title: res.message || '加载房间失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('加载房间列表失败:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    } finally {
        isLoading.value = false;
    }
};
// 添加滚动监听
const handleScroll = () => {
    const query = uni.createSelectorQuery().in(this);
    query.select('.container').boundingClientRect(rect => {
        if (rect && rect.bottom <= window.innerHeight + 50) {
            loadMoreRooms();
        }
    }).exec();
};
// 加载更多房间
const loadMoreRooms = () => {
    if (hasMoreRooms.value && !isLoading.value) {
        loadRooms(currentPage.value + 1);
    }
};

// 显示WiFi弹窗
const showWifiPopup = () => {
    wifiPopupVisible.value = true;
};

// 跳转到团购验券页面
const goToVoucher = () => {
    uni.navigateTo({
        url: '/pages/voucher/voucher'
    });
};

// 跳转到充值页面
const goToRecharge = () => {
    uni.navigateTo({
        url: '/pages/recharge/recharge'
    });
};

// 跳转到预约页面
const goToReserve = (roomId: string | number) => {
    console.log(`准备跳转到预约页面，房间ID: ${roomId}`);
    
    if (!roomId) {
        console.error('房间ID为空，无法跳转');
        uni.showToast({
            title: '房间信息不存在',
            icon: 'none'
        });
        return;
    }
    
    // 在参数中同时使用roomId和room_id以增加兼容性
    const url = `/pages/reserve/reserve?roomId=${roomId}&room_id=${roomId}`;
    console.log(`跳转URL: ${url}`);
    
    // 将参数保存到全局变量，以防URL参数传递失败
    uni.setStorageSync('RESERVE_ROOM_ID', roomId.toString());
    
    // 使用不同的导航方式尝试跳转
    uni.navigateTo({
        url,
        success: () => {
            console.log('跳转成功');
        },
        fail: (err) => {
            console.error('跳转失败:', err);
            // 尝试备用方式跳转
            setTimeout(() => {
                uni.redirectTo({
                    url,
                    success: () => console.log('重定向跳转成功'),
                    fail: (error) => {
                        console.error('重定向跳转失败:', error);
                        // 最后的备选方案
                        uni.switchTab({
                            url: '/pages/index/index',
                            success: () => {
                                setTimeout(() => {
                                    uni.navigateTo({
                                        url
                                    });
                                }, 300);
                            }
                        });
                    }
                });
            }, 100);
        }
    });
};

// 处理WiFi弹窗更新
const handleWifiPopupUpdate = (visible: boolean) => {
    wifiPopupVisible.value = visible;
};

// 处理全局tab切换事件
const handleGlobalTabChange = (tab: string) => {
    if (tab === 'home') return; // 当前已经是首页，不需要处理

    const routes: Record<string, string> = {
        'coupon': '/pages/coupon/coupon',
        'order': '/pages/order/order',
        'user': '/pages/user/user'
    };

    const url = routes[tab];
    if (!url) return;

    // 尝试使用redirectTo，这对非tabBar页面有效
    uni.redirectTo({
        url,
        fail: () => {
            // 如果失败则尝试强制刷新到新页面
            if (typeof window !== 'undefined') {
                window.location.replace('#' + url);
            }
        }
    });
};

// 初始化加载房间数据
onMounted(() => {
    uni.$on('tabChange', handleGlobalTabChange);
    loadRooms(1, true);
    // 添加滚动事件监听
    window.addEventListener('scroll', handleScroll);
});

// 组件销毁前移除事件监听
onBeforeUnmount(() => {
    uni.$off('tabChange', handleGlobalTabChange);
    // 移除滚动事件监听
    window.removeEventListener('scroll', handleScroll);
});
</script>
<style>
page {
    height: 100%;
}
.brand-swiper {
    width: 750rpx;
    height: 550rpx;
}
.container {
    min-height: 100%;
    background-color: #F5F5F5;
    display: flex;
    flex-direction: column;
}

.brand-section {
    background: #FFFFFF;
    border-radius: 0 0 20rpx 20rpx;
    overflow: hidden;
    position: relative;
}

.brand-banner {
    width: 750rpx;
    height: auto;
    display: block;
}

.shop-info {
    padding: 30rpx;
    position: relative;
    z-index: 1;
}

.business-info {
    display: flex;
    flex-direction: column;
    gap: 10rpx;
    margin-bottom: 20rpx;
    align-items: flex-start;
}

.shop-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #FFFFFF;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
    margin-bottom: 10rpx;
}

.business-time,
.business-address {
    font-size: 14px;
    color: #666666;
}

.quick-actions {
    display: flex;
    gap: 40rpx;
    justify-content: flex-end;
}

.action-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 14px;
    color: #7FB992;
}

.action-icon {
    width: 48rpx;
    height: 48rpx;
}

.feature-section {
    display: flex;
    justify-content: space-around;
    padding: 40rpx 20rpx;
    margin: 20rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
}

.feature-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
}

.feature-img {
    width: 120rpx;
    height: 120rpx;
    background-color: #FFFFFF;
    border-radius: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.feature-text {
    font-size: 14px;
    color: #333333;
}

.room-section {
    padding: 0 20rpx;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin: 30rpx 0 20rpx;
}

.empty-room {
    background: #FFFFFF;
    padding: 80rpx 0;
    border-radius: 16rpx;
    text-align: center;
    color: #999;
    font-size: 16px;
}

.room-card {
    background: #FFFFFF;
    border-radius: 16rpx;
    overflow: hidden;
    display: flex;
    padding: 24rpx;
    margin-bottom: 20rpx;
}

.room-image {
    width: 240rpx;
    height: 240rpx;
    border-radius: 12rpx;
    flex-shrink: 0;
}

.room-info {
    flex: 1;
    padding: 0 0 0 24rpx;
    display: flex;
    flex-direction: column;
}

.room-title {
    font-size: 16px;
    font-weight: bold;
    color: #333333;
    margin-bottom: 16rpx;
}

.room-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    margin-bottom: 16rpx;
}

.tag {
    padding: 4rpx 12rpx;
    background: rgba(127, 185, 146, 0.1);
    color: #7FB992;
    border-radius: 6rpx;
    font-size: 12px;
}

.price-info {
    margin-top: auto;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}

.price-wrapper {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
}

.price {
    display: flex;
    align-items: baseline;
}

.unit {
    font-size: 12px;
    color: #FF0000;
}

.amount {
    font-size: 20px;
    font-weight: bold;
    color: #FF0000;
    margin: 0 4rpx;
}

.package {
    font-size: 12px;
    color: #666666;
}

.package-price {
    color: #FF0000;
    font-weight: bold;
}

.book-btn {
    background: #7FB992;
    color: #FFFFFF;
    font-size: 14px;
    width: 120rpx;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 30rpx;
    margin: 0;
    padding: 0;
}

.switch-btn {
    background-color: #7FB992;
    color: #FFFFFF;
    font-size: 14px;
    padding: 0 30rpx;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 30rpx;
}

.feature-icon {
    width: 60rpx;
    height: 60rpx;
}

.load-more {
    text-align: center;
    padding: 20rpx 0;
    color: #666;
    font-size: 14px;
}

.load-more:active {
    opacity: 0.7;
}
</style>
